package com.jltx.zeus.arch.api

import okhttp3.Interceptor
import okhttp3.OkHttpClient

/**
 * @author aidenquan
 *         Created by junlintianxia on 2020/10/09.
 */
object OkhttpClientFactoryUtils {
    private const val CACHE_CONTROL = "Cache-Control"
    private const val cacheSize = 10 * 1024 * 1024 // 10 MiB

    var okHttpClient: OkHttpClient

    init {
//        val httpCacheDirectory =
//            File(App.app.applicationContext.getCacheDir(), "swCache")
//        val REWRITE_CACHE_CONTROL_INTERCEPTOR = Interceptor { chain ->
//            val originalResponse = chain.proceed(chain.request())
//            if (NetWorkUtil.isNetWorkAvailable(App.app.applicationContext)) {
//                val maxAge = 60 // 在线缓存在1分钟内可读取
//                originalResponse.newBuilder()
//                    .removeHeader("Pragma")
//                    .removeHeader(CACHE_CONTROL)
//                    .header(CACHE_CONTROL, "public, max-age=$maxAge")
//                    .build()
//            } else {
//                val maxStale = 60 * 60 * 24 * 28 // 离线时缓存保存4周
//                originalResponse.newBuilder()
//                    .removeHeader("Pragma")
//                    .removeHeader(CACHE_CONTROL)
//                    .header(CACHE_CONTROL, "public, only-if-cached, max-stale=$maxStale")
//                    .build()
//            }
//        }
//        val cache = Cache(httpCacheDirectory, cacheSize.toLong())

        /**
         * 增加头部信息的拦截器,获取解析今日视频需要用到
         */
        val mHeaderInterceptor =
            Interceptor { chain: Interceptor.Chain ->
                val builder = chain.request().newBuilder()
                builder.addHeader(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547"
                )
                builder.addHeader("Cache-Control", "max-age=0")
                builder.addHeader("Upgrade-Insecure-Requests", "1")
                builder.addHeader("X-Requested-With", "XMLHttpRequest")
                builder.addHeader(
                    "Cookie",
                    "uuid=\"w:f2e0e469165542f8a3960f67cb354026\"; __tasessionId=4p6q77g6q1479458262778; csrftoken=7de2dd812d513441f85cf8272f015ce5; tt_webid=36385357187"
                )
                chain.proceed(builder.build())
            }
        okHttpClient = OkHttpClient.Builder()
            .addInterceptor(mHeaderInterceptor)
//            .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
//            .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
//            .cache(cache)
            .build()
    }
}